<template>
    <div class="handle-btn-group">
        <el-dropdown v-for="item in outerLayerBtns" :key="item.name">
            <el-button
                :id="item.id || ''"
                :icon="item.icon"
                :type="item.type || ''"
                :plain="item.plain"
                :class="[{ warningClass: warningBtn.includes(item.value) }, item.class]"
                :disabled="item.alwaysDisabled || !btnsAuth[item.value]"
                @click="item.value && handleEvent(item.value, item.lang, item.interface)"
            >
                <i v-if="!item.hiddenIcon" class="iconfont f14" :class="item.svgIcon" />
                <el-tooltip
                    content="暂无权限"
                    placement="top"
                    effect="light"
                    :disabled="!item.alwaysDisabled"
                    popper-class="warning-btn"
                    :visible-arrow="false"
                >
                    <span :class="[!item.hiddenIcon ? 'mgl-6' : '']" style="outline: initial !important">{{ $t(item.lang) }}</span>
                </el-tooltip>
            </el-button>
            <el-dropdown-menu slot="dropdown">
                <el-dropdown-item v-for="(em, index) in item.dropdown" :key="index">
                    <span :class="em.class" @click="em.value && handleEvent(em.value, em.lang, em.interface)">{{ $t(em.lang) }}</span>
                </el-dropdown-item>
            </el-dropdown-menu>
        </el-dropdown>
        <!-- 打印 -->
        <el-dropdown v-if="printBtns.length > 0" size="small" trigger="click" placement="bottom" :hide-on-click="false">
            <el-button type="text" :disabled="printBtns[0].alwaysDisabled || !btnsAuth.print">
                <i class="iconfont f14 rbp-operate_print" />
                <el-tooltip
                    content="暂无权限"
                    placement="top"
                    effect="light"
                    :disabled="!printBtns[0].alwaysDisabled"
                    popper-class="warning-btn"
                    :visible-arrow="false"
                >
                    <span class="mgl-6">{{ $t('operationGroup.btns.print') }}</span>
                </el-tooltip>
            </el-button>
            <el-dropdown-menu slot="dropdown">
                <el-dropdown-item v-for="item in printList" :key="item.id" class="hover print-list">
                    <span class="f12 hover" @click="printPlain(item)">{{ item.templateName }}</span>
                    <span class="f12 color-info mgl-6" @click="preview(item)">{{ $t('commonWord.preview') }}</span>
                </el-dropdown-item>
                <el-dropdown-item>
                    <span @click="printManage">
                        {{ $t('commonWord.printingManagement') }}
                    </span>
                </el-dropdown-item>
            </el-dropdown-menu>
        </el-dropdown>
        <!-- 更多 用于放不常用的按钮 -->
        <el-dropdown v-if="moreContentBtns.length > 0" size="small" class="more-btn" :hide-on-click="false">
            <div class="el-dropdown-link mgl-20">
                <i class="iconfont rbp-operate_more f14 mgr-6" />
                <span class="f12">{{ $t('commonWord.more') }}</span>
            </div>
            <el-dropdown-menu slot="dropdown">
                <el-button
                    v-for="item in moreContentBtns"
                    :id="item.id || ''"
                    :key="item.name"
                    :icon="item.icon"
                    :type="item.type || ''"
                    :plain="item.plain"
                    :class="[{ warningClass: warningBtn.includes(item.value) }, item.class]"
                    class="block-btn"
                    :disabled="item.alwaysDisabled || !btnsAuth[item.value]"
                    @click="handleEvent(item.value, item.lang, item.interface)"
                >
                    <i v-if="!item.hiddenIcon" class="iconfont f14" :class="item.svgIcon" />
                    <el-tooltip
                        content="暂无权限"
                        placement="top"
                        effect="light"
                        :disabled="!item.alwaysDisabled"
                        popper-class="warning-btn"
                        :visible-arrow="false"
                    >
                        <span :class="[!item.hiddenIcon ? 'mgl-6' : '']">{{ $t(item.lang) }}</span>
                    </el-tooltip>
                </el-button>
            </el-dropdown-menu>
        </el-dropdown>
        <!-- 放上一页/下一页/操作记录的按钮 -->
        <el-button
            v-for="item in rightBtns"
            :id="item.id || ''"
            :key="item.name"
            :icon="item.icon"
            :type="item.type || ''"
            :plain="item.plain"
            :class="[{ warningClass: warningBtn.includes(item.value) }, item.class]"
            :disabled="!btnsAuth[item.value]"
            @click="handleEvent(item.value, item.lang, item.interface)"
        >
            <i v-if="!item.hiddenIcon" class="iconfont f14" :class="item.svgIcon" />
            <span :class="[!item.hiddenIcon ? 'mgl-6' : '']">{{ $t(item.lang) }}</span>
        </el-button>
        <slot name="followBtn" />
        <div v-if="showStatus" class="status-box">
            <slot name="beforeStatus" />
            <slot name="billStatus">
                <span :class="statusMap[billStatus]" class="f16">{{ $t('operationGroup.status')[billStatus] }}</span>
            </slot>
            <slot name="otherStatus" />
        </div>

        <print-manage ref="printManage" @update="getPrintList" />
    </div>
</template>

<script lang="ts">
import Vue from 'vue';
import Component from 'vue-class-component';
import { Prop, Watch } from 'vue-property-decorator';
import { DetailOperationConfig } from '@/typings';
import commonApi from '@/api/common-api/index';
import { PermissionConfig } from '@/store/modules/common-module';
import { Tools } from '@/utils/tools';
import libraryScript from '../../library';
const MORE_CONTENT_BTNS = ['import', 'export', 'unaudit', 'invalid', 'restore'];

const RIGHT_BTNS = ['prev', 'next', 'record'];

const PRINT_BTNS = ['print'];

@Component({
    name: 'common-operation',
    components: {
        baseDialog: () => import('@/components/base-dialog/index.vue'),
        baseTable: () => import('@/components/base-table/index.vue'),
        printManage: () => import('./printManage.vue')
    }
})
export default class detail extends Vue {
    @Prop({ required: true }) btnList: DetailOperationConfig[];
    @Prop({ default: true }) showStatus: boolean;
    // @Prop() billId
    @Prop() billStatus: string;
    @Prop() btnsAuth: Object;
    @Prop() btnPermission: string[];
    get billId() {
        return this.$store.state[this.$route.meta.moduleId].v_id.split('_')[0];
    }
    @Watch('btnList', { immediate: true })
    onBtnListChange(val) {
        if (val.length) {
            const outerLayer = [...MORE_CONTENT_BTNS, ...RIGHT_BTNS, ...PRINT_BTNS];
            const filterPermission: DetailOperationConfig[] = val;
            if (this.$store.state[this.$route.meta.moduleId]) {
                const permissionObj: PermissionConfig = this.$store.state[this.$route.meta.moduleId].v_permission;
                if (permissionObj) {
                    filterPermission.forEach((item) => {
                        if (!item.isValidatePermisssion) {
                            item.alwaysDisabled = !permissionObj.action.includes(item.operationId!);
                        }
                    });
                }
            }

            this.moreContentBtns = filterPermission.filter((item) => MORE_CONTENT_BTNS.includes(item.value));
            this.outerLayerBtns = filterPermission.filter((item) => !outerLayer.includes(item.value));
            this.rightBtns = filterPermission.filter((item) => RIGHT_BTNS.includes(item.value));
            this.printBtns = filterPermission.filter((item) => PRINT_BTNS.includes(item.value));
            if (this.printBtns.length) {
                this.$store.commit(
                    `${this.$route.meta.moduleId}/SET_PRINTREQUEST`,
                    Array.isArray(this.printBtns) && this.printBtns.length > 0 && this.printBtns[0]['interface']
                        ? this.printBtns[0]['interface']['apiUrl']
                        : null
                );
            }
        }
    }
    statusMap = {
        unaudit: 'danger',
        audit: 'success',
        reverseAudit: 'warning',
        invalid: 'invalid',
        disable: 'invalid',
        enable: 'success',
        hasAnalyze: 'success',
        analyzeDone: 'success'
    };
    moreContentBtns: DetailOperationConfig[] = [];
    outerLayerBtns: DetailOperationConfig[] = [];
    rightBtns: DetailOperationConfig[] = [];
    printBtns: DetailOperationConfig[] = [];
    printList: any[] = [];
    warningBtn: string[] = ['delete', 'invalid'];
    // 拥有打印管理的权限集合
    // printManageAuth: string[]=['700001', '700002', '700003'];

    mounted() {
        // 如果有打印功能 则获取打印列表
        if (this.btnList.findIndex((item) => item.value === 'print') > -1) {
            this.getPrintList();
        }
    }
    async getPrintList() {
        const res = await this._post({
            url: commonApi.getPrintList,
            data: {
                status: [100]
            }
        });
        if (res.code === 0) {
            this.printList = res.data;
        }
    }
    async printPlain(item) {
        const printConfig: DetailOperationConfig = this.printBtns[0];

        const printApi = printConfig.interface!.apiUrl;

        if (!printApi) {
            // throw new Error('请配置打印单据的API')
            this._message({ message: '请配置打印单据的API', type: 'warning' });
            return;
        }
        this.loadPrintScript(async () => {
            try {
                const printResponse = await this._get({
                    url: `${commonApi.getPrintDetail}/${item.id}`
                });
                // 获取到打印配置的详情模板
                const { templateFileContent } = printResponse.data;
                var report = new (window as any).Stimulsoft.Report.StiReport();
                // report.loadFile('/reports/billSalePlan.mrt')
                report.load(templateFileContent);
                report.dictionary.databases.clear();
                var dataSet = new (window as any).Stimulsoft.System.Data.DataSet('billData');
                // 获取到单据打印信息
                const res = await this._post({
                    url: printApi,
                    data: { ids: [this.billId] }
                });
                if (res.code === 0) {
                    dataSet.readJson(res.data);
                    report.regData('billData', 'billData', dataSet);
                    report.renderAsync(function () {
                        report.print();
                    });
                }
            } catch (error) {
                this._message({ message: '请求有误', type: 'error' });
            }
        });
    }
    // 加载打印引擎
    async loadPrintScript(callback) {
        if (!window['Stimulsoft']) {
            const scriptStatus: boolean[] = [];
            const printScript = libraryScript.print;
            for (const file of printScript) {
                const res = await Tools.synchronizationLoad(file);
                if (typeof res === 'boolean') {
                    scriptStatus.push(res);
                }
            }
            if (scriptStatus.indexOf(false) === -1) {
                window['Stimulsoft'].Base.Localization.StiLocalization.addLocalizationFile('Localization/zh-CHS.xml', false, 'zh-CHS');
                window['Stimulsoft'].Base.Localization.StiLocalization.cultureName = 'zh-CHS';
                window['Stimulsoft'].Base.StiLicense.loadFromFile('stimulsoft/license.key');
                callback();
            } else {
                this.$message.error('打印脚本加载失败,请联系管理员');
            }
        } else {
            callback();
        }
    }
    async preview(item) {
        const printConfig: DetailOperationConfig = this.printBtns[0];

        const printApi = printConfig.interface!.apiUrl;

        if (!printApi) {
            // throw new Error('请配置打印单据的API')
            this._message({ message: '请配置打印单据的API', type: 'warning' });
            return;
        }
        const routeData = this.$router.resolve({
            name: 'printPreview',
            params: {
                printId: item.id,
                ids: this.billId,
                printApi,
                moduleId: this.$route.meta.moduleId
            },
            query: {
                printId: item.id,
                ids: this.billId,
                printApi,
                moduleId: this.$route.meta.moduleId
            }
        });
        window.open(routeData.href, '_blank');
    }
    handleEvent(event, name, config) {
        const confirmText = this.$t('dialogPrompt')[event];
        if (confirmText && ['cancel', 'delete'].includes(event)) {
            this._confirm({ content: confirmText })
                .then(() => {
                    this.$emit(event, Object.assign({}, config, { name }));
                })
                .catch(() => {
                    return false;
                });
        } else {
            this.$emit(event, Object.assign({}, config, { name }));
        }
    }
    printManage() {
        this.$nextTick(() => {
            (this.$refs['printManage'] as any).open();
        });
    }
}
</script>
<style lang="scss">
@import 'src/styles/variables.scss';
.handle-btn-group {
    // .el-dropdown-menu--small {
    //   margin: 0 !important;
    //   top: 146px !important;
    //   padding: 6px 8px !important;
    // }
    .el-dropdown-menu__item.hover.print-list {
        display: flex;
        justify-content: space-between;
    }
    .el-button--text {
        color: $colorTextPrimary;
        // padding: 7px 12px;
        &:hover {
            color: $basic;
        }
    }
    .warningClass.el-button--text {
        &:hover {
            color: $danger;
        }
    }
}
</style>
<style scoped lang="scss">
@import 'src/styles/variables.scss';
.block-btn {
    display: block;
    margin: 0 8px !important;
}
.handle-btn-group {
    background: #fff;
    height: 44px;
    line-height: 44px;
    padding: 0 16px;
    .status-box {
        float: right;
        font-size: 12px;
    }
    /deep/.el-button--text {
        color: $colorTextPrimary;
        padding: 7px 0 7px 20px !important;
        &:hover {
            color: $basic;
        }
    }
    /deep/ .warningClass.el-button--text {
        &:hover {
            color: $danger;
        }
    }
    /deep/.el-button.is-disabled {
        color: $colorTextPlaceholder;
    }
    /deep/.el-button + .el-button {
        margin-left: 0;
    }
    /deep/.is-disabled.is-plain {
        background-color: #fff !important;
        border-color: #eee !important;
        color: $colorTextPlaceholder !important;
        &:hover {
            background-color: #fff !important;
            border-color: #eee !important;
            color: $colorTextPlaceholder !important;
        }
    }
    .status-box {
        display: flex;
        flex-direction: column;
        line-height: 1;
        align-items: center;
        height: 44px;
        justify-content: space-around;
    }
    .status {
        color: $success;
        padding: 7px 0;
    }
    .prev-btn {
        position: relative;
        margin-left: 20px !important;
        &::before {
            position: absolute;
            top: 6px;
            left: 0;
            content: '';
            width: 1px;
            height: 20px;
            background: $borderColorBase;
        }
    }
}
.base-dialog {
    /deep/.el-dialog__body {
        padding: 20px 16px;
    }
}
.warning-btn {
    background: $warning;
    color: $warning;
}
</style>
